<script lang='ts' setup>
import { formatTime, timestampToTime } from "@/utils/common.methods";
import { ref, defineProps, onMounted, onUnmounted } from "vue";
const now = ref(0);
const second = ref(0);
const millisecond = ref(0);
const date = ref("");
const dateZh = ref("");

let timeInterval = null;

onMounted(() => {
  now.value = new Date().getTime();
  timeInterval = setInterval(() => {
    now.value = new Date().getTime();
  }, 1000);
});

onUnmounted(() => {
  clearInterval(timeInterval);
});

function init(dateTemp: Date): void {
  second.value = Math.floor(dateTemp.getTime() / 1000);
  millisecond.value = dateTemp.getTime();
  date.value = formatTime(new Date(second.value * 1000));
  dateZh.value = formatTime(new Date(second.value * 1000));
}

/** 时间戳 */
function onTimeStamp(now?: number): void {
  if (now) second.value = now;
  second.value =
    String(second.value).length > 11 ? second.value : second.value * 1000;
  const time = Number(second.value);
  init(new Date(time));
}

function onDate(): void {
  init(new Date(date.value));
}
</script>
<template>
  <div class="time">
    <div class="title hr">在线 时间戳转换</div>
    <div class="cell flex">
      <div class="sub-title">现在</div>
      <span class="now" @click="onTimeStamp(now)"> {{ now }} </span>
    </div>
    <div class="cell flex">
      <div class="sub-title">时间戳</div>
      <t-input placeholder="请输入内容" v-model="second" />
      <t-button class="btn" :disabled="!second" @click="onTimeStamp()">转换</t-button>
    </div>
    <div class="cell flex">
      <div class="sub-title">时间</div>
      <t-input placeholder="请输入内容" v-model="date" />
      <t-button class="btn" :disabled="!date" @click="onDate">转换</t-button>
    </div>

    <div class="result">
      <div class="sub-title">结果 </div>
      <div class="item flex">
        <div class="sub-title">北京时间</div>
        <span class="span">{{ date }}</span>
        <span class="span">{{ dateZh }}</span>
      </div>
      <div class="item flex">
        <div class="sub-title">时间戳 /s </div>
        {{ second }}
      </div>
      <div class="item flex">
        <div class="sub-title">时间戳 /ms</div>
        {{ millisecond }}
      </div>
    </div>
  </div>
</template>
<style lang='scss' scoped>
.time {
  padding: 40px;
  width: 100%;

  .title {
    font-size: 25px;
  }

  .cell {
    margin: 10px 0;

    .btn {
      margin-right: 20px;
    }

    .t-input__wrap {
      width: 200px;
      margin-right: 20px;
    }
  }

  .sub-title {
    width: 70px;
    font-size: 14px;
    color: #666;
    text-align-last: justify;
    margin-right: 15px;

    &::after {
      content: "：";
    }
  }

  .result {
    margin-top: 20px;

    .item {
      margin: 20px 0;

      .span {
        margin-right: 20px;
      }
    }
  }
}
</style>